from sqlalchemy import delete, insert, select, update

from owl_admin.ext import db
from owl_ai.domain.chat_entity import ChatFileMessage
from owl_ai.domain.po import AIChatFileMessagePO
from owl_common.sqlalchemy.model import ColumnEntityList
from owl_common.sqlalchemy.transaction import Transactional


class ChatFileMapper:
    default_fields = ["id", "chat_id", "message_id", "name", "path", "suffix", "create_time", "update_time",
                      "create_user", "update_user"]

    default_columns = ColumnEntityList(AIChatFileMessagePO, default_fields, False)

    @classmethod
    @Transactional(db.session)
    def insert_file(cls, chat_file_message: ChatFileMessage) -> int:
        fields = {"chat_id", "message_id", "name", "path", "suffix", "create_time", "update_time", "create_user",
                  "update_user"}

        data = chat_file_message.model_dump(include=fields, exclude_none=True, exclude_unset=True)
        stmt = insert(AIChatFileMessagePO).values(data)
        out = db.session.execute(stmt).inserted_primary_key
        return out[0] if out else 0

    @classmethod
    def find_file_by_id(cls, file_id: int):
        stmt = select(*cls.default_columns).where(AIChatFileMessagePO.id == file_id)
        row = db.session.execute(stmt).one_or_none()
        return cls.default_columns.cast(row, ChatFileMessage)
